package com.zhu.service.admin.controller.web;
import com.zhu.commons.utils.JwtInfo;
import com.zhu.commons.utils.JwtUtils;
import com.zhu.commons.utils.R;
import com.zhu.service.admin.service.IMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.validation.Validator;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;


@Controller
@Slf4j
@Api(tags = "微信登录模块")
//@CrossOrigin
@RequestMapping("/api/admin/weixin")
public class WeixinApiController {
    @Value("${wx.open.appId}")
    private String appId;
    @Value("${wx.open.appSecret}")
    private String appSecret;
    @Value("${wx.open.redirectUri}")
    private String redirectUri;
    @Autowired
    private IMemberService memberService;

    /**
     * 未开通
     * @param session
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     */
    @ApiOperation(value = "微信登陆")
    @GetMapping("/login")
    public String getQrConnect(HttpSession session, HttpServletResponse response) throws UnsupportedEncodingException {
        response.setHeader("Access-Control-Allow-Origin","*");
        //组装url：https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=回调地址&response_type=code&scope=snsapi_login&state=随机数#wechat_redirect
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        String encode = URLEncoder.encode(redirectUri, "UTF-8");
        //生成随机数 防止csrf攻击
        String state = UUID.randomUUID().toString();
        session.setAttribute("wx_state",state);
        String wxUrl=String.format(baseUrl,appId,encode,state);
        //跳转
        return "redirect:"+wxUrl;
    }



}
